package com.trxy.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class KaptchaController {
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping("/kaptcha.jpg")
    void kaptcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        String codeStr = defaultKaptcha.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, codeStr);//将验证码文本放入session中
        BufferedImage bi = defaultKaptcha.createImage(codeStr);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        out.flush();
        out.close();
    }
}
